﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using ReadMap.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net;

namespace DataParser
{
    public static class SVGParser
    {
        static JArray mapid2stationid;
        static List<XmlNode> stationTexts = new List<XmlNode>();
        public static void init() 
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Data\\Map.xml"));
            var circles = new List<Station>();
            var nodes = doc.ChildNodes;
            var root = nodes[2];

            mapid2stationid = JArray.Parse(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\Data\\MapID2StationID.json"));
            FindNode(root, "text", ref stationTexts);


            FindNode(root, "circle", stationTexts, ref circles);

            float x, y;

            foreach (Station s in circles)
            {
                if (s.Name == "松江南站")
                {

                }
            }
            var stationPaths = new List<XmlNode>();
            FindAllStationPath(root, ref stationPaths, ref circles);

            //读StationInfo并将其序列化到Out.json
            var json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Data\\StationInfo.json");
            var obj = JObject.Parse(json);
            var array = obj["levels"][0]["locations"].Value<JArray>();
            var index = 0;
            foreach (var circle in circles)
            {
                foreach (JObject newObj in array)
                {
                    if (newObj["title"].Value<string>() == circle.Name)
                    {
                        circle.StationID = newObj["id"].Value<string>();
                        if (newObj["font_size"] != null)
                            circle.FontSize = newObj["font_size"].Value<int>();
                        if (newObj["line"] != null)
                            circle.Line = newObj["line"].ToObject<List<int>>();
                    }
                }
                index++;
            }

            //根据车站名，查询所有线路

            foreach (Station s in circles)
            {
                Console.WriteLine(s.Name);
                var result = HttpGet(
                    "http://marketing.cyberspaceit.cn/interface/metromap/metromap.aspx",
                    new Dictionary<string, string>()
                    {
                        {"func","stationInfo"},
                        {"station_code",s.StationID.Substring(2,s.StationID.Length-2) }
                    });
                var info = JArray.Parse(result)[0].ToObject<JObject>();
                s.NumberID = info["stat_id"].Value<int>();
                s.EnName = info["name_en"].Value<string>();
                s.Pinyin = info["pinyin"].Value<string>();
                if (info["lines"].Value<string>() != string.Empty)
                {

                    var linesStr = info["lines"].ToObject<string>().Replace("，",",").Split(',');
                    s.Line = new List<int>();
                    foreach (string lineStr in linesStr)
                    {
                        s.Line.Add(Convert.ToInt32(lineStr));
                    }
                }
            }


            var text = JsonConvert.SerializeObject(circles, Newtonsoft.Json.Formatting.Indented);
            var path = AppDomain.CurrentDomain.BaseDirectory + "\\Data\\Out.json";
            File.WriteAllText(path, text);
        }
        static SVGParser()
        {
            
        }
        private static string HttpGet(string url, Dictionary<string, string> query)
        {
            //拼接查询语句
            if (query != null && query.Count != 0)
            {
                StringBuilder sb = new StringBuilder(url);
                sb.Append("?");
                foreach (var pair in query)
                {
                    sb.Append(pair.Key);
                    sb.Append("=");
                    sb.Append(pair.Value);
                    sb.Append("&");
                }
                sb.Remove(sb.Length - 1, 1);
                url = sb.ToString();
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8";
            request.Accept = "application/json; text/javascript, */*; q=0.01";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;
            WebResponse response = null;
            string responseStr = null;
            response = request.GetResponse();
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            return responseStr;
        }
        private static void FindAllStationPath(XmlNode root, ref List<XmlNode> result, ref List<Station> list)
        {
            foreach (XmlNode child in root.ChildNodes)
            {
                FindAllStationPath(child, ref result, ref list);
            }
            if (root.Name == "path" && root.Attributes["id"].Value.IndexOf("station") != -1)
            {
                result.Add(root);
                AddNodeToStation(root, null, ref list);
            }
        }
        private static void FindNode(XmlNode node, string name, ref List<XmlNode> list)
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                FindNode(child, name, ref list);
            }
            if (node.Name == name)
            {
                list.Add(node);
            }
        }
        private static void AddNodeToStation(XmlNode node, List<XmlNode> texts, ref List<Station> list)
        {
            var s = new Station();
            s.MapID = node.Attributes["id"].InnerText;
            if (node.Name == "circle")
            {
                s.x = Convert.ToSingle(node.Attributes["cx"].InnerText);
                s.y = Convert.ToSingle(node.Attributes["cy"].InnerText);
                s.r = Convert.ToSingle(node.Attributes["r"].InnerText);
            }
            else if (node.Name == "path")
            {
                var dAttr = node.Attributes["d"];
                if (dAttr == null)
                {
                    ;
                }
                var temp = dAttr.Value;
                var subLeft = temp.Substring(temp.IndexOf(' ') + 1);
                var result = subLeft.Substring(0, subLeft.IndexOf(' ')).Split(',');
                s.x = Convert.ToSingle(result[0]);
                s.y = Convert.ToSingle(result[1]);
                s.r = 12;
            }
            else
            {
                ;
            }
            s.FindID = s.MapID.Replace("station", "");

            var parentTransformAttr = node.ParentNode.Attributes["transform"];
            if (parentTransformAttr == null)
                parentTransformAttr = node.ParentNode.ParentNode.Attributes["transform"];
            if (parentTransformAttr != null)
                s.ParentTransform = parentTransformAttr.InnerText;
            foreach (JObject station in mapid2stationid)
            {
                var stationID = station["key"].ToString();
                var stationName = station["value"].ToString();

                if (stationID == s.FindID)
                {
                    s.Name = stationName;

                    //根据名字在text节点找到对应的节点
                    foreach (XmlNode text in stationTexts)
                    {
                        if (text.InnerXml == stationName)
                        {
                            //找到了对应的text节点
                            var attr = text.Attributes["transform"];
                            if (attr != null)
                            {
                                s.TextTransform = text.Attributes["transform"].InnerText.ToString();
                            }
                            else
                            {
                                s.TextX = Convert.ToSingle(text.Attributes["x"].InnerText);
                                s.TextY = Convert.ToSingle(text.Attributes["y"].InnerText);
                            }
                        }
                    }
                }
            }
            //找名字


            list.Add(s);
        }
        private static void FindNode(XmlNode node, string name, List<XmlNode> texts, ref List<Station> list)
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                FindNode(child, name, texts, ref list);
            }
            if (node.Name == name && node.Attributes["id"].InnerText.IndexOf("station") != -1)
            {
                AddNodeToStation(node, texts, ref list);
            }
        }
    }
}
